<template>
  <div class="container">
    <div class="app-container">
      <!-- 角色管理内容 -->
      <div class="role-operate">
        <el-button
          type="primary"
          size="mini"
          @click="
            showDialog = true;
            isAgree = true;
          "
        >添加员工</el-button>
        <el-table :data="list">
          <el-table-column label="角色" prop="name" width="200px">
            <template v-slot="{ row }">
              <input
                v-if="row.isEdit"
                v-model="row.editRow.name"
                type="text"
                size="mini"
              >
              <span v-else>{{ row.name }}</span>
            </template>
          </el-table-column>
          <el-table-column label="是否启用" prop="state">
            <template v-slot="{ row }">
              <el-switch
                v-if="row.isEdit"
                v-model="row.editRow.state"
                :active-value="1"
                :inactive-value="0"
              />
              <span v-else>
                {{ row.state === 1 ? "已启用" : row.state === 0 ? "未启用" : "无" }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="角色描述" prop="description">
            <template v-slot="{ row }">
              <el-input
                v-if="row.isEdit"
                v-model="row.editRow.description"
                type="textarea"
              />
              <span v-else>{{ row.description }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template v-slot="{ row }">
              <template v-if="row.isEdit">
                <el-button
                  size="mini"
                  type="primary"
                  @click="btnEdit(row)"
                >确认</el-button>
                <el-button
                  size="mini"
                  @click="row.isEdit = false"
                >取消</el-button>
              </template>
              <template v-else>
                <el-button type="text" @click="btnPermission(row.id)">权限管理</el-button>
                <el-button type="text" @click="btnEditRow(row)">编辑</el-button>

                <el-popconfirm
                  title="这是一段内容确定删除吗？"
                  @onConfirm="confirmDel(row.id)"
                >
                  <el-button
                    slot="reference"
                    style="margin-left: 10px"
                    size="mini"
                    type="text"
                  >删除</el-button>
                </el-popconfirm>
              </template>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件显示 -->
        <el-row type="flex" justify="end" align="center">
          <el-pagination
            layout="prev, pager, next"
            :page-size="pageTotal.pagesize"
            :current-page="pageTotal.page"
            :total="total"
            @current-change="updatePage"
          />
        </el-row>
      </div>
      <!-- 表单内容 -->
      <el-dialog
        :visible.sync="showDialog"
        :title="isAgree ? '新增角色' : '编辑角色'"
        @close="btnCancel"
      >
        <el-form
          ref="role"
          label-width="120px"
          :model="RoleFrom"
          :rules="rules"
        >
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="RoleFrom.name" size="mini" />
          </el-form-item>
          <el-form-item label="角色名称" prop="state">
            <el-switch v-model="RoleFrom.state" />
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input
              v-model="RoleFrom.description"
              size="mini"
              type="textarea"
              :rows="3"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="btnOk">确认</el-button>
            <el-button @click="btnCancel">取消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
      <el-dialog title="权限管理" :visible.sync="showRole">
        <!-- node-ID表示唯一选择值为ID -->
        <el-tree
          ref="parTree"
          node-key="id"
          :props="{label:'name'}"
          show-checkbox
          default-expand-all
          :data="permissionData"
          :default-checked-keys="permIds"
        />
        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button size="mini" type="primary" @click="assiginOk">确定</el-button>
            <el-button size="mini" @click="showRole=false">取消</el-button>
          </el-col>
        </el-row>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import { getRoleList, addRole, deleRole, updateRole, getRoleDetail, assignPerm } from '@/api/role'
import { getPermissionList } from '@/api/permission'
import { transListToTreeData } from '@/utils/index'
export default {
  name: 'Role',
  data() {
    return {
      permIds: [],
      currentId: null, // 中间变量用于接收ID
      permissionData: [], // 分配权限数据
      showRole: false, // 权限管理弹出层
      list: [], // 列表数据
      total: 0, // 页码总数
      showDialog: false, // 是否显示弹层
      isAgree: true, // 是否添加角色
      // 分页
      pageTotal: {
        page: 2,
        pagesize: 10
      },
      RoleFrom: {
        name: '',
        description: '',
        state: 0
      },
      rules: {
        name: [
          {
            required: true,
            message: '角色名不能为空',
            trigger: 'blur'
          }
        ],
        description: [
          { required: true, message: '角色描述不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getRole()
  },
  methods: {
    async getRole() {
      // 解构赋值
      const { rows, total } = await getRoleList(this.pageTotal)
      // 要传入页码参数
      this.list = rows
      this.list.forEach((item) => {
        // item.isEdit = false // 添加一个属性 初始值为false
        // 数据响应式的问题  数据变化 视图更新
        // 添加的动态属性 不具备响应式特点
        // this.$set(目标对象, 属性名称, 初始值) 可以针对目标对象 添加的属性 添加响应式
        this.$set(item, 'isEdit', false)
        // 定义输入框内容
        this.$set(item, 'editRow', {
          name: item.name,
          state: item.state,
          description: item.description
        })
      })
      this.total = total
    },
    updatePage(newPage) {
      // s更新新的页面，把最新页给到当前页面
      this.pageTotal.page = newPage
      // console.log(11)
      // 换完新页码的时候请求数据
      this.getRole()
    },
    btnOk() {
      this.$refs.role.validate(async(isOk) => {
        if (isOk) {
          await addRole(this.RoleFrom)
          this.$message.success('添加角色成功')
          // 传入要修改的ID的同时还要传入整个表单
          // 更新信息
          this.getRole()
          this.btnCancel()
        }
      })
    },
    btnCancel() {
      this.$refs.role.resetFields()
      this.showDialog = false
    },
    // 编辑按钮，展示编辑表框
    btnEditRow(row) {
      // console.log(row)
      row.isEdit = true
      // 更新缓存数据
      row.editRow = { ...row }
      row.editRow = JSON.parse(JSON.stringify(row))
      // row.editRow.name = row.name
      // row.editRow.state = row.state
      // row.editRow.description = row.description
    },
    // 确定按钮，进行非空判断
    async btnEdit(row) {
      if (row.editRow.name && row.editRow.description) {
        await updateRole({
          ...row.editRow,
          id: row.id
        })
        this.$message.success('更新角色成功')
        // 不用浅拷贝赋值不生效
        Object.assign(row, {
          ...row.editRow,
          // 退出编辑模式
          isEdit: false
        })
        this.getRole()
      } else {
        this.$message.warning('信息不能为空')
      }
    },
    async confirmDel(id) {
      // 首先 删除接口需要获取用户ID 需要进行参数接收
      // 通过ID删除角色，如果点击删除就返回删除的接口 带上id
      // 再提示消息
      // 再更新视图
      await deleRole(id)
      this.$message.success('删除角色成功')
      if (this.list.length === 1) this.pageTotal.page--
      this.getRole()
    },
    async btnPermission(id) {
      this.currentId = id
      const { permIds } = await getRoleDetail(id)
      this.permIds = permIds
      // console.log(this.permissionData)
      this.showRole = true
      this.permissionData = transListToTreeData(await getPermissionList(), 0)
    },
    async assiginOk() {
      await assignPerm({
        id: this.currentId,
        permIds: this.$refs.parTree.getCheckedKeys()
      })
      this.$message.success('修改权限成功')
      this.showRole = false
    }

    // async btnEdit(id) {
    //   // 传参要进行赋值
    //   this.showDialog = true
    //   const res = await getRoleInfo(id)
    //   console.log(res)
    //   this.RoleFrom = res
    //   this.isAgree = false
    // }
  }
}
</script>
